package localserver;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Iterator;
import java.util.List;

import common.Player;

public class UDPTools {

	static int bufferSize = 1000;

	public static void UDPServer(int UDPPort, String geolocation) {

		DatagramSocket serverSocket = null;

		try {
			serverSocket = new DatagramSocket(UDPPort);

			byte[] bufferIn = new byte[bufferSize];
			byte[] bufferOut = new byte[bufferSize];

			while (true) {
				DatagramPacket request = new DatagramPacket(bufferIn,
						bufferIn.length);
				// System.out.println("Before receive:");
				serverSocket.receive(request);

				common.Tools.writeLog(
						"server",
						geolocation,
						"New UDP Request received from :"
								+ (new String(request.getData())).trim()
								+ " server", true);
				String stringOut = getLocalUserStatus();
				bufferOut = stringOut.getBytes();
				DatagramPacket reply = new DatagramPacket(bufferOut,
						bufferOut.length, request.getAddress(),
						request.getPort());
				serverSocket.send(reply);
				common.Tools
						.writeLog(
								"server",
								geolocation,
								"A UDP response was sent to:"
										+ (new String(request.getData()))
												.trim()
										+ " server with the result: "
										+ stringOut, true);
			}

		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (serverSocket != null)
				serverSocket.close();
		}

	}

	public static String getLocalUserStatus() {
		int onlineCount = 0;
		int offlineCount = 0;
		PlayerHashTable hashTable = PlayerHashTable.getInstance();
		Iterator ite = hashTable.values().iterator();
		while (ite.hasNext()) {
			List<Player> list = (List<Player>) ite.next();

			for (int i = 0; i < list.size(); i++) {
				Player p = list.get(i);
				if (p.isOnline()) {
					onlineCount++;
				} else {
					offlineCount++;
				}
			}
		}
		String response = onlineCount + " online, " + offlineCount
				+ " offline.";

		// System.out.println("I did send a response:"+ response);
		return response;

	}
}